package com.czh.gzskzn.shenke3;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.czh.gzskzn.shenke3.Activity.GonGaoActivity;
import com.czh.gzskzn.shenke3.Activity.NewActivity;
import com.czh.gzskzn.shenke3.Activity.ShuiFeiActivity.ShuiFeiJiaonaActivity;
import com.czh.gzskzn.shenke3.Activity.YeJianActivity;
import com.czh.gzskzn.shenke3.Util.ImagePaperAdapter;
import com.paradoxie.autoscrolltextview.VerticalTextview;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by gzsk on 2017/4/18.
 * name  陈忠红
 * email czhhx15599109256@163.com
 *
 */


public class ShoYeFrag extends Fragment implements View.OnClickListener{

    private WebView wngye;
    private TextView tv_sosuo;
    private LayoutInflater inflater;
    private ViewPager mviewPager;
    /**用于小圆点图片*/
    private List<ImageView> dotViewList;
    /**用于存放轮播效果图片*/
    private List<ImageView> list;

   private LinearLayout dotLayout;
    private ImageButton imageButton;
    private int currentItem  = 0;//当前页面

    boolean isAutoPlay = true;//是否自动轮播

    private ScheduledExecutorService scheduledExecutorService;


//    private UPMarqueeView upview1;;

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if(msg.what == 150){
                mviewPager.setCurrentItem(currentItem);
            }
        }

    };

    View homzhuyefrag;
    List<String> data = new ArrayList<>();
    List<View> views = new ArrayList<>();

    //    布局实例化
    private LinearLayout shuiFei,gonGao,xinWen,shuiZhi,yiJian,gouMai;
//    imageView
    private ImageView imShuiFei,imGonGao,imXingWen,imShuiZhi,imYiJian,imGouMai;
//    TexeView
    private TextView tvShuiFei,tvGonGao,tvXingWen,tvShuiZhi,tvYiJian,tvGouMai;

// 自定义
    private VerticalTextview ziTi1;
    private ArrayList<String> titleList = new ArrayList<String>();
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        homzhuyefrag = inflater.inflate(R.layout.homzhuyefrag, container, false);
        intiView1();
//        WanYe();

        yeMianQiHuan();


/*************         轮播      **********/

//        inflater = LayoutInflater.from(getActivity());
        mviewPager = (ViewPager) homzhuyefrag.findViewById(R.id.myviewPager);
        dotLayout = (LinearLayout)homzhuyefrag.findViewById(R.id.dotLayout);
        dotLayout.removeAllViews();

        initView();

        DianJi();

        initdata();

        if(isAutoPlay){
            startPlay();
        }
        setView();
//        upview1.setViews(views);

        lunBo();

        return homzhuyefrag;
    }

    private void lunBo() {

        titleList.add("家人给2岁孩子喝这个，孩子智力倒退10岁!!!");
        titleList.add("iPhone8最感人变化成真，必须买买买买!!!!");
        titleList.add("简直是白菜价！日本玩家33万甩卖15万张游戏王卡");
        titleList.add("iPhone7价格曝光了！看完感觉我的腰子有点疼...");
        titleList.add("主人内疚逃命时没带够，回废墟狂挖30小时！");
        titleList.add("竟不是小米乐视！看水抢了骁龙821首发了！！！");
        ziTi1.setTextList(titleList);//加入显示内容,集合类型
        ziTi1.setText(15, 1, Color.parseColor("#000000"));//设置属性,具体跟踪源码
        ziTi1.setTextStillTime(5000);//设置停留时长间隔
        ziTi1.setAnimTime(1000);//设置进入和退出的时间间隔

        ziTi1.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
            @Override
            public void onItemClick(int i) {
                Toast.makeText(getActivity(), "点击了 : " + titleList.get(i), Toast.LENGTH_SHORT).show();
            }
        });

    }


    private void DianJi() {
        tv_sosuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(),ZhuYeSoActivity.class);
                startActivity(i);
            }
        });


    }

    private void yeMianQiHuan() {


    }

    private void WanYe() {
        //设置WebView属性，能够执行Javascript脚本
        wngye.getSettings().setJavaScriptEnabled(false);
        //加载需要显示的网页
        wngye.loadUrl("http://www.51cto.com/");
        //设置Web视图
        wngye.setWebViewClient(new HelloWebViewClient());
        wngye.getSettings().setUseWideViewPort(true);
        wngye.getSettings().setLoadWithOverviewMode(true);
//        wngye.setBackgroundColor(Color.parseColor("#000000"));
        wngye.getSettings().setDefaultFontSize(5);
    }

    private void intiView1() {

//
        ziTi1 = (VerticalTextview) homzhuyefrag.findViewById(R.id.text12);

        shuiFei = (LinearLayout) homzhuyefrag.findViewById(R.id.Ll_ShuiFei);
        gonGao = (LinearLayout) homzhuyefrag.findViewById(R.id.Ll_tinzshui);
        xinWen = (LinearLayout) homzhuyefrag.findViewById(R.id.Ll_xingwen);
        shuiZhi = (LinearLayout) homzhuyefrag.findViewById(R.id.Ll_suizhi);
        yiJian = (LinearLayout) homzhuyefrag.findViewById(R.id.Ll_yijian);
        gouMai = (LinearLayout) homzhuyefrag.findViewById(R.id.Ll_goumai);

        imShuiFei = (ImageView) homzhuyefrag.findViewById(R.id.im_shuifei);
        imGonGao = (ImageView) homzhuyefrag.findViewById(R.id.iv_tinshui);
        imXingWen = (ImageView) homzhuyefrag.findViewById(R.id.iv_xinwen);
        imShuiZhi = (ImageView) homzhuyefrag.findViewById(R.id.iv_shuizhi);
        imYiJian = (ImageView) homzhuyefrag.findViewById(R.id.iv_yijian);
        imGouMai = (ImageView) homzhuyefrag.findViewById(R.id.im_gomai);


        tvShuiFei = (TextView) homzhuyefrag.findViewById(R.id.tv_shuifei);
        tvGonGao = (TextView) homzhuyefrag.findViewById(R.id.tv_tinshui);
        tvXingWen = (TextView) homzhuyefrag.findViewById(R.id.tv_xinwen);
        tvShuiZhi = (TextView) homzhuyefrag.findViewById(R.id.tv_shuizhi);
        tvYiJian = (TextView) homzhuyefrag.findViewById(R.id.tv_yijian);
        tvGouMai = (TextView) homzhuyefrag.findViewById(R.id.tv_goumai);

        tv_sosuo = (TextView) homzhuyefrag.findViewById(R.id.tv_sosuokuang);
        wngye = (WebView) homzhuyefrag.findViewById(R.id.xinwen);

//        upview1 = (UPMarqueeView) homzhuyefrag.findViewById(R.id.upview1);


        shuiFei.setOnClickListener(this);
        gonGao.setOnClickListener(this);
        xinWen.setOnClickListener(this);
        shuiZhi.setOnClickListener(this);
        yiJian.setOnClickListener(this);
        gouMai.setOnClickListener(this);



    }

    private void initView() {

        dotViewList = new ArrayList<ImageView>();
        list = new ArrayList<ImageView>();


        for (int i = 0; i < 4; i++) {
            ImageView dotView = new ImageView(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ActionBar.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

            params.leftMargin = 15;//设置小圆点的外边距
            params.rightMargin = 15;

            params.height = 25;//设置小圆点的大小
            params.width = 25;

            if(i == 0){
                dotView.setBackgroundResource(R.drawable.point_pressed);
            }else{

                dotView.setBackgroundResource(R.drawable.point_unpressed);
            }
            dotLayout.addView(dotView, params);

            dotViewList.add(dotView);
            //上面是动态添加了四个小圆点
        }


        ImageView img1 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item, null);
        ImageView img2 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item, null);
        ImageView img3 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item, null);
        ImageView img4 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item, null);

        img1.setBackgroundResource(R.drawable.banner);
        img2.setBackgroundResource(R.drawable.main_img1);
        img3.setBackgroundResource(R.drawable.main_img2);
        img4.setBackgroundResource(R.drawable.main_img3);

        list.add(img1);
        list.add(img2);
        list.add(img3);
        list.add(img4);

        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),"asasasas",Toast.LENGTH_SHORT).show();
            }
        });

        ImagePaperAdapter adapter = new ImagePaperAdapter((ArrayList)list);

        mviewPager.setAdapter(adapter);
        mviewPager.setCurrentItem(0);
        mviewPager.setOnPageChangeListener(new MyPageChangeListener());

    }
    /**
     * 开始轮播图切换
     */
    private void startPlay(){
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
        //根据他的参数说明，第一个参数是执行的任务，第二个参数是第一次执行的间隔，第三个参数是执行任务的周期；
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Ll_ShuiFei:
//                Toast.makeText(getActivity(),"sasa",Toast.LENGTH_SHORT).show();
                Intent i = new Intent(getActivity(),ShuiFeiJiaonaActivity.class);
                startActivity(i);

            break;
            case R.id.Ll_tinzshui:
                Intent ii = new Intent(getActivity(),GonGaoActivity.class);
                startActivity(ii);
//                Toast.makeText(getActivity(),"111",Toast.LENGTH_SHORT).show();
             break;
            case R.id.Ll_xingwen:
                Intent iii = new Intent(getActivity(),NewActivity.class);
                startActivity(iii);
                break; case R.id.Ll_suizhi:
                Toast.makeText(getActivity(),"sasa",Toast.LENGTH_SHORT).show();
                break;
            case R.id.Ll_yijian:
                Intent iiii = new Intent(getActivity(),YeJianActivity.class);
                startActivity(iiii);
                break;
            case R.id.Ll_goumai:
                Toast.makeText(getActivity(),"222",Toast.LENGTH_SHORT).show();
                break;

        }
    }

    /**
     *执行轮播图切换任务
     *
     */
    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (mviewPager) {
                currentItem = (currentItem+1)%list.size();
                handler.sendEmptyMessage(150);
            }
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     *
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    System.out.println(" 手势滑动，空闲中");
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    System.out.println(" 界面切换中");
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (mviewPager.getCurrentItem() == mviewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        mviewPager.setCurrentItem(0);
                        System.out.println(" 滑动到最后一张");
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (mviewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        mviewPager.setCurrentItem(mviewPager.getAdapter().getCount() - 1);
                        System.out.println(" 滑动到第一张");
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
            //这里面动态改变小圆点的被背景，来实现效果
            currentItem = pos;
            for (int i = 0; i < dotViewList.size(); i++) {
                if (i == pos) {
                    ((View) dotViewList.get(pos)).setBackgroundResource(R.drawable.point_pressed);
                } else {
                    ((View) dotViewList.get(i)).setBackgroundResource(R.drawable.point_unpressed);
                }
            }
        }
    }

        //Web视图
    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    /**
     * 初始化需要循环的View
     * 为了灵活的使用滚动的View，所以把滚动的内容让用户自定义
     * 假如滚动的是三条或者一条，或者是其他，只需要把对应的布局，和这个方法稍微改改就可以了，
     */
    private void setView() {
        for (int i = 0; i < data.size(); i = i + 2) {
            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.item_view, null);
            //初始化布局的控件
            TextView tv1 = (TextView) moreView.findViewById(R.id.tv1);
            TextView tv2 = (TextView) moreView.findViewById(R.id.tv2);
            //进行对控件赋值
            tv1.setText(data.get(i).toString());
            if (data.size() > i + 1) {
                //因为淘宝那儿是两条数据，但是当数据是奇数时就不需要赋值第二个，所以加了一个判断，还应该把第二个布局给隐藏掉
                tv2.setText(data.get(i + 1).toString());
            }else {
                moreView.findViewById(R.id.rl2).setVisibility(View.GONE);
            }

            //添加到循环滚动数组里面去
            views.add(moreView);
        }
    }

    /**
     * 初始化数据
     */
    private void initdata() {
        data = new ArrayList<>();

    }
    @Override
    public void onResume() {
        super.onResume();
        ziTi1.startAutoScroll();
    }
}